package com.hxt.webpasser.regular;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.hxt.webpasser.transport.xml.Rule;
import com.hxt.webpasser.utils.CommonUtil;
import com.hxt.webpasser.utils.FillParamValueUtil;
import com.hxt.webpasser.utils.StringUtil;

public class ForEachRule implements DecideRule{

	
	public List<Object> handle(Rule rule, List<Object> contentList, Map valueMap) {
		
		String begin = rule.getBegin();
		String end = rule.getEnds();
		String step = rule.getStep();
		String items = rule.getItems();
		List<Rule> rules = rule.getRules();
		
		List<Object> returnList = new ArrayList<Object>();
		
		AcceptDecideRuleHandler acceptDecideRuleHandler=new AcceptDecideRuleHandler();
		//List obList = null;
		Object orgObject= contentList==null?null:contentList.get(0);
		if(StringUtil.isNotEmpty(items)){
			
			List obList = (List) FillParamValueUtil.getValueByKeyTemplate(items, valueMap, orgObject);
			if(obList!=null){
				for(Object orgItem:obList){
					List<Object> valList=acceptDecideRuleHandler.handleRulesForPersistent(rules, StringUtil.toString(orgItem),valueMap);
					returnList.addAll(valList);
				}
				
			}
			
			contentList.set(0, obList);
		}else{
			
			int stepInt = StringUtil.isNotEmpty(step)? CommonUtil.toInteger(FillParamValueUtil.getValueByKeyTemplate(step, valueMap, orgObject)):1;
			int beginInt = StringUtil.isNotEmpty(begin)? CommonUtil.toInteger(FillParamValueUtil.getValueByKeyTemplate(begin, valueMap, orgObject)):1;
			int endInt = StringUtil.isNotEmpty(end)? CommonUtil.toInteger(FillParamValueUtil.getValueByKeyTemplate(end, valueMap, orgObject)):1;
			int index = beginInt;
			int i=0;
			for(;index<=endInt;index=index+stepInt){
				
				valueMap.put("_index_", index);
				List<Object> valList=acceptDecideRuleHandler.handleRulesForPersistent(rules, StringUtil.toString(orgObject),valueMap);
				returnList.addAll(valList);
				
				i++;
			}
			valueMap.remove("_index_");
		}
		
		
		return returnList;
	}

}
